package com.hongdezhi.web.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hongdezhi.domain.Employee;
import com.hongdezhi.service.EmpService;

/**
 * @author Hong de zhi
 * @version V1.0
 * 1:管理员 2:普通用户
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获得用户名和密码
		String nameid = request.getParameter("username");
		String password = request.getParameter("password");
		//1:管理员 2:普通用户
		//2.1判断验证码 是否一致
		String userCode = request.getParameter("formCode");
		String serverCode = (String) request.getSession().getAttribute("Code");
		EmpService emp = new EmpService();
		
		if(serverCode.equals(userCode)){
			if("1".equals(emp.login(nameid, password))){ //管理员
				Employee user = new Employee();
				user.setNameid(nameid);
				user.setPassword(password);
				request.getSession().setAttribute("user", user);
				
				// 跳转至管理员页
				response.sendRedirect(request.getContextPath()+"/manager.jsp");
			}else if("2".equals(emp.login(nameid, password))){ //普通用户
				Employee user = new Employee();
				user.setNameid(nameid);
				user.setPassword(password);
				request.getSession().setAttribute("user", user);
				
				// 跳转至员工页
				response.sendRedirect(request.getContextPath()+"/common.jsp");
			}else{
				request.setAttribute("errerMsg", "alert('没有该管理员')");
				//http://localhost:8080/hrm/jsp/login.jsp
				request.getRequestDispatcher("/login.jsp").forward(request,response);
			}
		}else{
			request.setAttribute("errerMsg", "alert('验证码错误')");
			request.getRequestDispatcher("/login.jsp").forward(request,response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
